<?php

class Ext_Generic_Authentication implements Zend_Auth_Adapter_Interface
{

    private $_username = null;

    private $_password = null;

    private $_applicationId = null;

    private $_db = null;

    // users may be grouped by owner. An owner can be a
    // customer, organization, etc.
    private $_ownerId = null;

    /**
     * Sets username and password for authentication
     *
     * @return void
     */
    public function __construct( $username, $password, $applicationId, $db = null )
    {
        $this->_username = $username;
        $this->_password = $password;
        $this->_db = $db;
        $this->_applicationId = $applicationId;
    }

    /**
     * Performs an authentication attempt
     *
     * @throws Zend_Auth_Adapter_Exception If authentication cannot
     *                                     be performed
     * @return Zend_Auth_Result
     */
    public function authenticate()
    {

        if ( strtoupper( $this->_username ) == 'ROOT' ) {
            $config = Zend_Registry::get('config');
            if ( !empty( $config ) && isset( $config->rootPass ) ) {
                $pass = $config->rootPass;
                if ( crypt( $this->_password, $pass ) == $pass ) {
                    return new Zend_Auth_Result(
                        Zend_Auth_Result::SUCCESS,
                        new Ext_Auth_RootUser()
                    );
                }
            }
        }
        $userModel = new Ext_Model_User( $this->_db );
        $user = $userModel->getAuthenticatedUser(
            $this->_username
            , $this->_password
            , $this->_ownerId
        );
        // if we succeded we save the user in the session
        // and forward to the correct action
        if ( ! empty( $user ) ) {
            return new Zend_Auth_Result(
                Zend_Auth_Result::SUCCESS,
                new Ext_Auth_AuthenticatedUser(
                    $user,
                    $this->_applicationId
                )
            );
        }
        // return failed login
        return new Zend_Auth_Result( Zend_Auth_Result::FAILURE, null );
    }

    public function setOwner( $newOwnerId )
    {
        $this->_ownerId = $newOwnerId;
    }
}